package com.gitlab.lucky.weixin.web.pay;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.model.PlatformData;
import com.gitlab.lucky.common.dao.model.WeixinGzhIntegrationRecord;
import com.gitlab.lucky.common.dao.model.WeixinGzhRecharge;
import com.gitlab.lucky.common.dao.model.WeixinGzhUser;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.service.ConfigDataService;
import com.gitlab.lucky.common.service.PlatformDataService;
import com.gitlab.lucky.common.utils.CookieUtil;
import com.gitlab.lucky.common.utils.TemplateMessageUtil;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import com.gitlab.lucky.weixin.service.WeixinGzhMsgService;
import com.gitlab.lucky.weixin.service.WeixinGzhIntegrationRecordService;
import com.gitlab.lucky.weixin.service.WeixinGzhRechargeService;
import com.gitlab.lucky.weixin.service.WeixinGzhUserService;
import com.gitlab.lucky.weixin.web.model.Notify;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-10-30 22:10
 **/
@Controller
public class PayJsController {
    public static final Logger LOGGER = LoggerFactory.getLogger(PayJsController.class);
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private WeixinGzhMsgService weixinGzhMsgService;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;
    @Autowired
    private PlatformDataService platformDataService;
    @Autowired
    private WeixinGzhRechargeService weixinGzhRechargeService;
    @Autowired
    private ConfigDataService configDataService;

    private final static String PAY_JS_API = "https://payjs.cn/api/jsapi";
    private final static String NOTIFY_URL = "http://wm.cgygeo.com/notifyUrl";
    private final static String URL = "http://wm.cgygeo.com";
    private final static String PAY_JS_URL = "https://payjs.cn/api/openid";

    @GetMapping("pay")
    public ModelAndView pay(HttpServletRequest request, HttpServletResponse response, String openid,Integer platform) throws IOException {
        PlatformData platformData = platformDataService.getPlatform(platform);
        String openId = CookieUtil.getCookie(request, Constant.OPENID+platform);
        String payJsOpenId = CookieUtil.getCookie(request, Constant.PAY_JS_OPENID+platform);
        if (StringUtils.isBlank(payJsOpenId) && StringUtils.isNotBlank(openid)) {
            Cookie cookie = new Cookie(Constant.PAY_JS_OPENID+platform, openid);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            payJsOpenId = openid;
        }
        if (StringUtils.isBlank(openId) || StringUtils.isBlank(payJsOpenId)) {
            response.sendRedirect("/code?platform="+ platform + "&redirectUrl="+PAY_JS_URL+"?mchid="+platformData.getMchId()+"!callback_url="+URL+"/pay/?platform="+platform);
            return null;
        }

        ModelAndView m = new ModelAndView();
        m.setViewName("pay");
        m.addObject("platform",platform);
        m.addObject("openid", openId);
        m.addObject("payjs_openid", payJsOpenId);
        return m;
    }

    @PostMapping("payJs")
    @ResponseBody
    public String payJs(String payJsOpenId, Integer type, String openId,Integer platform) {
        PlatformData platformData = platformDataService.getPlatform(platform);
        LOGGER.info("提交支付:PAY_JS_OPEN_ID:{},OPEN_ID:{},平台:{}", payJsOpenId, openId,platform);
        if (type != 0 && type != 1 && type != 2 && type != 3) {
            return null;
        }
        Map<String, Object> map = new TreeMap<>();
        map.put("mchid", platformData.getMchId());
        if (type == 0) {
            map.put("total_fee", 300);
        }
        if (type == 1) {
            map.put("total_fee", 1000);
        }
        if (type == 2) {
            map.put("total_fee", 2000);
        }
        map.put("out_trade_no", UUID.randomUUID().toString().substring(0, 8));
        map.put("body", platformData.getMchName());
        map.put("attach", openId+","+platform);
        map.put("notify_url", NOTIFY_URL);
        map.put("openid", payJsOpenId);
        map.put("sign", WeixinUtil.getSign(map,platformData.getPayJsKey()));
        String post = HttpUtil.createPost(PAY_JS_API).form(map).execute().body();
        String jsonObject = JSONObject.parseObject(post).toJSONString();
        return jsonObject;
    }

    @PostMapping("notifyUrl")
    @ResponseBody
    @Transactional
    public String notifyUrl(Notify notify) {
        if (notify == null||notify.getReturn_code() != 1||StringUtils.isBlank(notify.getOut_trade_no())) {
            LOGGER.info("支付失败");
            return "success";
        }
        LOGGER.info("订单号:{}", notify.getOut_trade_no());
        String attach = notify.getAttach();
        String openId = attach.split(",")[0];
        Integer platform = Integer.parseInt(attach.split(",")[1]);
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platform);
        WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
        if (notify.getTotal_fee() == 300) {
            weixinGzhIntegrationRecord.setIntegration("+"+48);
            weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 48);
        }
        if (notify.getTotal_fee() == 1000) {
            weixinGzhIntegrationRecord.setIntegration("+"+200);
            weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 200);
        }
        if (notify.getTotal_fee() == 2000) {
            weixinGzhIntegrationRecord.setIntegration("+"+500);
            weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + 500);
        }

        LOGGER.info("充值成功加积分:{},用户openId:{},平台:{}", weixinGzhUser.getIntegration(), weixinGzhUser.getOpenid(),platform);
        weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);
        //积分流水记录
        weixinGzhIntegrationRecord.setIntegrationBalance(weixinGzhUser.getIntegration());
        weixinGzhIntegrationRecord.setOpenId(weixinGzhUser.getOpenid());
        weixinGzhIntegrationRecord.setPlatform(platform);
        weixinGzhIntegrationRecord.setCreateTime(new Date());
        weixinGzhIntegrationRecord.setType(CodeEnum.RECHARGE.getCode());
        weixinGzhIntegrationRecordService.insert(weixinGzhIntegrationRecord);
        //充值记录
        WeixinGzhRecharge weixinGzhRecharge = new WeixinGzhRecharge();
        weixinGzhRecharge.setCreateTime(new Date());
        weixinGzhRecharge.setMoney(notify.getTotal_fee()/100.00);
        weixinGzhRecharge.setOpenId(openId);
        weixinGzhRecharge.setParentOpenId(weixinGzhUser.getQrSceneStr());
        weixinGzhRecharge.setPlatform(platform);
        weixinGzhRecharge.setState(Constant.NO_WITHDRAWAL);
        weixinGzhRechargeService.insertSelective(weixinGzhRecharge);
        JSONObject json = configDataService.getConfig(platform);
        if(json.getInteger(Constant.IS_TEMPLATE) == 1 && !StringUtils.isBlank(Constant.PAY_TEMPLATEID)) {
            List<TemplateMessageUtil> templateParams = new ArrayList<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            TemplateMessageUtil first = new TemplateMessageUtil("first", "恭喜您充值成功", "");
            String integration = weixinGzhIntegrationRecord.getIntegration().substring(1, weixinGzhIntegrationRecord.getIntegration().length());
            TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", notify.getTotal_fee()/100+"元充"+integration+"积分", "");
            TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", df.format(new Date()), "");
            TemplateMessageUtil keyword3 = new TemplateMessageUtil("keyword3", weixinGzhUser.getIntegration()+"积分", "");
            TemplateMessageUtil remark = new TemplateMessageUtil("remark", "", "");
            templateParams.add(first);
            templateParams.add(keyword1);
            templateParams.add(keyword2);
            templateParams.add(keyword3);
            templateParams.add(remark);
            String url = Constant.DOMAIN_URL+"/integrationRecordView?openId="+openId+"&platform="+platform;
            weixinGzhMsgService.sendWarningByWechat(openId, platform, json.getString(Constant.PAY_TEMPLATEID), templateParams,url);
        }else{
            weixinGzhMsgService.resultServerText(weixinGzhUser.getOpenid(), String.format(Constant.PAY_MSG, weixinGzhUser.getIntegration()), platform);
        }

        return "success";
    }
}
